//图片懒加载指令 v-lazy
import defaultImg from '@/assets/images/defaultImg.jpg'

// 全局指令
export default (app: any) => {
    // 图片懒加载指令
    app.directive('lazy', {
        mounted(el: any, binding: any) {
            const io = new IntersectionObserver(
                ([{isIntersecting}]) => {
                    if (isIntersecting) {
                        //isIntersecting判断是否进入视图
                        io.unobserve(el) //进入视图后，停止监听
                        el.onerror = () => {
                            //加载失败显示默认图片
                            el.src = defaultImg
                        }
                        el.src = binding.value //进入视图后，把指令绑定的值赋值给src属性，显示图片
                    }
                },
                {threshold: 0}
            )
            io.observe(el) //观察指令绑定的dom
        }
    })
}
